Page({
  data: {
    registrationType: 'individual', // individual 或 company
    isEditMode: false, // 是否为修改模式
    registrationId: '', // 修改时的注册记录ID
    formData: {
      // 通用字段
      avatar: '', // 头像/LOGO
      name: '',
      phone: '',
      location: '',
      category: '',
      experience: '',
      description: '',
      specialties: '',
      certifications: '',

      // 个人师傅特有字段
      realName: '',
      idCard: '',

      // 公司特有字段
      companyName: '',
      businessLicense: '',
      legalRepresentative: '',
      registeredCapital: '',
      companyAddress: ''
    },
    // 基于服务分类的专业分类
    categories: [
      { key: 'sme_market', name: '中小市场', description: '企宽延伸、商宽延伸、维保服务等' },
      { key: 'information_integration', name: '信息化集成', description: '系统集成、软件开发、数据服务等' },
      { key: 'engineering_construction', name: '工程施工', description: '建筑施工、装修装饰、基础设施等' },
      { key: 'network_maintenance', name: '网络维护', description: '网络设备维护、故障排除、优化升级等' },
      { key: 'smart_home', name: '智能家居', description: '智能设备安装、系统集成、维护服务等' },
      { key: 'measurement_testing', name: '计量检测', description: '设备检测、质量检验、标准认证等' },
      { key: 'material_equipment', name: '材料设备', description: '设备供应、材料配送、安装调试等' }
    ],
    submitting: false,
    categoryIndex: 0,
    currentCategoryName: '请选择专业分类',

    // 经验选项
    experienceOptions: ['1年以下', '1-3年', '3-5年', '5-10年', '10年以上'],
    experienceIndex: 0,

    // 贵州省地区数据
    guizhouRegions: {
      '贵阳市': ['南明区', '云岩区', '花溪区', '乌当区', '白云区', '观山湖区', '开阳县', '息烽县', '修文县', '清镇市'],
      '遵义市': ['红花岗区', '汇川区', '播州区', '桐梓县', '绥阳县', '正安县', '道真县', '务川县', '凤冈县', '湄潭县', '余庆县', '习水县', '赤水市', '仁怀市'],
      '六盘水市': ['钟山区', '六枝特区', '水城区', '盘州市'],
      '安顺市': ['西秀区', '平坝区', '普定县', '镇宁县', '关岭县', '紫云县'],
      '毕节市': ['七星关区', '大方县', '黔西市', '金沙县', '织金县', '纳雍县', '威宁县', '赫章县'],
      '铜仁市': ['碧江区', '万山区', '江口县', '玉屏县', '石阡县', '思南县', '印江县', '德江县', '沿河县', '松桃县'],
      '黔西南州': ['兴义市', '兴仁市', '普安县', '晴隆县', '贞丰县', '望谟县', '册亨县', '安龙县'],
      '黔东南州': ['凯里市', '黄平县', '施秉县', '三穗县', '镇远县', '岑巩县', '天柱县', '锦屏县', '剑河县', '台江县', '黎平县', '榕江县', '从江县', '雷山县', '麻江县', '丹寨县'],
      '黔南州': ['都匀市', '福泉市', '荔波县', '贵定县', '瓮安县', '独山县', '平塘县', '罗甸县', '长顺县', '龙里县', '惠水县', '三都县']
    },

    // 选中的地区
    selectedRegions: [],
    selectedCities: {}, // 记录每个城市是否全选
    showRegionPicker: false
  },

  onLoad(options) {
    const type = options.type || 'individual'
    const editMode = options.edit === 'true'
    const registrationId = options.id || ''

    this.setData({
      registrationType: type,
      isEditMode: editMode,
      registrationId: registrationId
    })

    const title = editMode
      ? (type === 'individual' ? '修改个人师傅信息' : '修改施工公司信息')
      : (type === 'individual' ? '个人师傅注册' : '施工公司注册')

    wx.setNavigationBarTitle({
      title: title
    })

    // 如果是编辑模式，加载现有数据
    if (editMode && registrationId) {
      this.loadRegistrationData(registrationId)
    }
  },

  // 加载注册数据（编辑模式）
  async loadRegistrationData(registrationId) {
    wx.showLoading({
      title: '加载数据中...',
      mask: true
    })

    try {
      const result = await wx.cloud.callFunction({
        name: 'getUserRegistrationStatus',
        data: {}
      })

      if (result.result && result.result.success && result.result.data.hasRegistration) {
        const registration = result.result.data.registration

        console.log('📋 加载的注册数据:', registration)
        console.log('🔍 服务地区相关字段检查:')
        console.log('  - registration.serviceRegions:', registration.serviceRegions)
        console.log('  - registration.location:', registration.location)

        // 处理服务地区数据
        const serviceRegions = registration.serviceRegions || []
        const locationText = serviceRegions.length > 0 ? serviceRegions.join('、') : (registration.location || '')

        console.log('🔧 处理后的地区数据:')
        console.log('  - serviceRegions数组:', serviceRegions)
        console.log('  - locationText:', locationText)

        // 填充表单数据
        const updateData = {
          'formData.avatar': registration.avatar || '',
          'formData.name': registration.name || '',
          'formData.phone': registration.phone || '',
          'formData.location': locationText,
          'formData.category': registration.category || '',
          'formData.experience': registration.experience || '',
          'formData.description': registration.description || '',
          'formData.specialties': Array.isArray(registration.specialties) ? registration.specialties.join('，') : (registration.specialties || ''),
          'formData.certifications': Array.isArray(registration.certifications) ? registration.certifications.join('，') : (registration.certifications || ''),
          selectedRegions: serviceRegions
        }

        // 填充个人师傅特有字段
        if (registration.type === 'individual') {
          updateData['formData.realName'] = registration.realName || registration.name || ''
          updateData['formData.idCard'] = registration.idCard || ''
        }

        // 填充公司特有字段
        if (registration.type === 'company') {
          updateData['formData.companyName'] = registration.companyName || registration.name || ''
          updateData['formData.businessLicense'] = registration.businessLicense || ''
          updateData['formData.legalRepresentative'] = registration.legalRepresentative || ''
          updateData['formData.registeredCapital'] = registration.registeredCapital || ''
          updateData['formData.companyAddress'] = registration.companyAddress || registration.location || ''
        }

        // 设置分类相关数据
        if (registration.category && this.data.categories) {
          const categoryIndex = this.data.categories.findIndex(cat => cat.key === registration.category)
          if (categoryIndex > -1) {
            updateData.categoryIndex = categoryIndex
            updateData.currentCategoryName = this.data.categories[categoryIndex].name
            updateData['formData.categoryName'] = this.data.categories[categoryIndex].name
          }
        }

        // 设置经验相关数据
        if (registration.experience && this.data.experienceOptions) {
          const experienceIndex = this.data.experienceOptions.findIndex(exp => exp === registration.experience)
          if (experienceIndex > -1) {
            updateData.experienceIndex = experienceIndex
          }
        }

        console.log('🔧 数据初始化状态检查:')
        console.log('  - categories数组:', this.data.categories ? `${this.data.categories.length}项` : '未定义')
        console.log('  - experienceOptions数组:', this.data.experienceOptions ? `${this.data.experienceOptions.length}项` : '未定义')
        console.log('🔧 分类索引:', updateData.categoryIndex, '分类名称:', updateData.currentCategoryName)
        console.log('🔧 经验索引:', updateData.experienceIndex, '经验:', registration.experience)

        this.setData(updateData, () => {
          // 数据设置完成后的回调
          console.log('✅ 数据设置完成，当前selectedRegions:', this.data.selectedRegions)

          // 更新城市全选状态（如果有选中的地区）
          if (this.data.selectedRegions && this.data.selectedRegions.length > 0) {
            this.updateCitySelectStatus()
            console.log('🔄 已更新城市全选状态')
          }
        })

        console.log('✅ 注册数据加载成功:', registration.name)
        console.log('📝 已填充字段:', Object.keys(updateData))
        console.log('🔍 表单数据详情:')
        console.log('  - 头像:', updateData['formData.avatar'] ? '已设置' : '未设置')
        console.log('  - 姓名:', updateData['formData.name'])
        console.log('  - 电话:', updateData['formData.phone'])
        console.log('  - 地区:', updateData['formData.location'])
        console.log('  - 分类:', updateData['formData.category'], '→', updateData.currentCategoryName)
        console.log('  - 经验:', updateData['formData.experience'])
        console.log('  - 技能:', updateData['formData.specialties'])
        console.log('  - 资质:', updateData['formData.certifications'])
        console.log('  - 介绍:', updateData['formData.description'] ? '已填写' : '未填写')
        console.log('  - 服务地区数组:', updateData.selectedRegions)

        // 延迟调用测试方法，确保数据已设置
        setTimeout(() => {
          this.testRegionDisplay()
        }, 100)
      } else {
        throw new Error('未找到注册数据')
      }

    } catch (error) {
      console.error('❌ 加载注册数据失败:', error)
      wx.showModal({
        title: '加载失败',
        content: '无法加载注册数据，请返回重试',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 选择头像/LOGO
  selectAvatar() {
    const { registrationType } = this.data
    const title = registrationType === 'individual' ? '选择头像' : '选择公司LOGO'

    wx.showActionSheet({
      itemList: ['从相册选择', '拍照'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.chooseFromAlbum()
        } else if (res.tapIndex === 1) {
          this.takePhoto()
        }
      }
    })
  },

  // 从相册选择
  chooseFromAlbum() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.uploadAvatar(tempFilePath)
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 拍照
  takePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.uploadAvatar(tempFilePath)
      },
      fail: (error) => {
        console.error('拍照失败:', error)
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        })
      }
    })
  },

  // 上传头像到云存储
  async uploadAvatar(tempFilePath) {
    wx.showLoading({
      title: '上传中...',
      mask: true
    })

    try {
      // 生成唯一文件名
      const timestamp = Date.now()
      const random = Math.floor(Math.random() * 1000)
      const fileExtension = tempFilePath.split('.').pop()
      const fileName = `team-avatars/${timestamp}_${random}.${fileExtension}`

      // 上传到云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: fileName,
        filePath: tempFilePath
      })

      console.log('头像上传成功:', uploadResult.fileID)

      // 更新表单数据
      this.setData({
        'formData.avatar': uploadResult.fileID
      })

      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })

    } catch (error) {
      wx.hideLoading()
      console.error('头像上传失败:', error)
      wx.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      })
    }
  },

  // 显示地区选择器
  showRegionSelector() {
    console.log('🗺️ 显示地区选择器')
    console.log('  - 当前selectedRegions:', this.data.selectedRegions)
    console.log('  - 当前selectedCities:', this.data.selectedCities)

    this.setData({
      showRegionPicker: true
    })

    // 禁止页面滚动
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
  },

  // 隐藏地区选择器
  hideRegionSelector() {
    console.log('❌ 隐藏地区选择器（点击遮罩层）')
    this.setData({
      showRegionPicker: false
    })
  },

  // 防止触摸穿透
  preventTouchMove() {
    // 阻止事件传播，防止背景页面滚动
    return false
  },

  // 切换地区选择
  toggleRegion(e) {
    const region = e.currentTarget.dataset.region
    const { selectedRegions } = this.data

    const index = selectedRegions.indexOf(region)
    if (index > -1) {
      // 取消选择
      selectedRegions.splice(index, 1)
      console.log('❌ 取消选择地区:', region)
    } else {
      // 添加选择
      selectedRegions.push(region)
      console.log('✅ 选择地区:', region)
    }

    this.setData({
      selectedRegions: selectedRegions
    })

    // 更新城市全选状态
    this.updateCitySelectStatus()

    console.log('📊 当前已选择地区数量:', selectedRegions.length)
  },

  // 切换城市全选
  toggleCity(e) {
    const city = e.currentTarget.dataset.city
    const { guizhouRegions, selectedRegions, selectedCities } = this.data
    const counties = guizhouRegions[city]

    const isAllSelected = selectedCities[city]

    console.log('🏙️ 切换城市全选:', city, '当前状态:', isAllSelected ? '已全选' : '未全选')

    if (isAllSelected) {
      // 取消全选
      counties.forEach(county => {
        const region = city + county
        const index = selectedRegions.indexOf(region)
        if (index > -1) {
          selectedRegions.splice(index, 1)
        }
      })
      console.log('❌ 取消全选', city, '移除了', counties.length, '个地区')
    } else {
      // 全选
      counties.forEach(county => {
        const region = city + county
        if (selectedRegions.indexOf(region) === -1) {
          selectedRegions.push(region)
        }
      })
      console.log('✅ 全选', city, '添加了', counties.length, '个地区')
    }

    this.setData({
      selectedRegions: selectedRegions
    })

    this.updateCitySelectStatus()

    console.log('📊 当前已选择地区数量:', selectedRegions.length)
  },

  // 更新城市全选状态
  updateCitySelectStatus() {
    const { guizhouRegions, selectedRegions } = this.data
    const selectedCities = {}

    Object.keys(guizhouRegions).forEach(city => {
      const counties = guizhouRegions[city]
      const selectedCount = counties.filter(county => {
        return selectedRegions.indexOf(city + county) > -1
      }).length

      selectedCities[city] = selectedCount === counties.length
    })

    this.setData({
      selectedCities: selectedCities
    })
  },

  // 确认地区选择
  confirmRegionSelection() {
    const { selectedRegions } = this.data

    console.log('🎯 确认地区选择，当前选择数量:', selectedRegions.length)

    if (selectedRegions.length === 0) {
      wx.showToast({
        title: '请至少选择一个服务地区',
        icon: 'none'
      })
      return
    }

    // 更新表单数据
    this.setData({
      'formData.location': selectedRegions.join('、'),
      showRegionPicker: false
    })

    console.log('✅ 地区选择确认完成，选择的服务地区:', selectedRegions)
    console.log('📝 表单location字段已更新:', selectedRegions.join('、'))
  },

  // 防止弹窗关闭（阻止事件冒泡）
  preventClose() {
    console.log('🛡️ 防止地区选择弹窗关闭')
    // catchtap 已经阻止了事件冒泡，这里只需要空实现
  },

  // 防止触摸穿透
  preventTouchMove() {
    console.log('🛡️ 防止触摸穿透')
    // catchtouchmove 已经阻止了触摸事件穿透
  },

  // 测试地区数据显示
  testRegionDisplay() {
    console.log('🧪 测试地区数据显示:')
    console.log('  - selectedRegions:', this.data.selectedRegions)
    console.log('  - selectedRegions.length:', this.data.selectedRegions.length)
    console.log('  - formData.location:', this.data.formData.location)
    console.log('  - selectedCities:', this.data.selectedCities)

    // 如果地区数据为空，设置一些测试数据
    if (!this.data.selectedRegions || this.data.selectedRegions.length === 0) {
      console.log('⚠️ 地区数据为空，设置测试数据')
      this.setData({
        selectedRegions: ['贵阳市南明区', '贵阳市云岩区'],
        'formData.location': '贵阳市南明区、贵阳市云岩区'
      }, () => {
        this.updateCitySelectStatus()
        console.log('✅ 测试数据设置完成')
      })
    }
  },

  // 输入处理
  onInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择专业分类
  onCategoryChange(e) {
    const { categories } = this.data
    const index = e.detail.value
    const category = categories[index]

    this.setData({
      'formData.category': category.key,
      categoryIndex: index,
      currentCategoryName: category.name
    })
  },

  // 选择从业经验
  onExperienceChange(e) {
    const { experienceOptions } = this.data
    const index = e.detail.value
    const experience = experienceOptions[index]

    console.log('📅 选择从业经验:', experience)

    this.setData({
      experienceIndex: index,
      'formData.experience': experience
    })
  },

  // 提交注册申请
  async submitRegistration() {
    if (this.data.submitting) return

    const { registrationType, formData } = this.data

    // 表单验证
    if (!this.validateForm()) {
      return
    }

    this.setData({ submitting: true })

    try {
      console.log('📝 提交注册申请:', { type: registrationType, data: formData })

      // 准备提交数据
      const submitData = {
        ...formData,
        type: registrationType,
        typeName: registrationType === 'individual' ? '个人师傅' : '施工公司',
        serviceRegions: this.data.selectedRegions, // 服务地区数组
        auditStatus: 'pending', // 审核状态：pending(待审核)、approved(已通过)、rejected(已拒绝)
        canReceiveOrders: false, // 是否可以接单
        auditTime: null, // 审核时间
        auditReason: '', // 审核备注
        rating: 0,
        completedProjects: 0,
        status: 'available', // 工作状态：available(可接单)、busy(忙碌中)
        joinDate: new Date().toISOString().split('T')[0],
        tags: [],
        priceRange: '', // 价格范围
        submitTime: new Date(),
        createTime: new Date(),
        updateTime: new Date()
      }

      // 处理专业技能和资质证书（转换为数组）
      if (submitData.specialties) {
        submitData.specialties = submitData.specialties.split('，').map(s => s.trim()).filter(s => s)
      }
      if (submitData.certifications) {
        submitData.certifications = submitData.certifications.split('，').map(s => s.trim()).filter(s => s)
      }

      // 根据模式调用不同的云函数
      const cloudFunctionName = this.data.isEditMode ? 'updateTeamRegistration' : 'submitTeamRegistration'
      const cloudFunctionData = this.data.isEditMode
        ? { ...submitData, registrationId: this.data.registrationId }
        : submitData

      const result = await wx.cloud.callFunction({
        name: cloudFunctionName,
        data: cloudFunctionData
      })

      if (result.result && result.result.success) {
        console.log(`✅ ${this.data.isEditMode ? '修改' : '注册'}申请提交成功:`, result.result)
      } else {
        throw new Error(result.result?.error || '提交失败')
      }
      
      const successTitle = this.data.isEditMode ? '修改成功' : '申请提交成功'
      const successContent = this.data.isEditMode
        ? `您的${registrationType === 'individual' ? '个人师傅' : '施工公司'}注册信息已修改并重新提交审核！\n\n我们将在3-5个工作日内完成审核，审核结果将通过短信或电话通知您。`
        : `您的${registrationType === 'individual' ? '个人师傅' : '施工公司'}注册申请已提交成功！\n\n我们将在3-5个工作日内完成审核，审核结果将通过短信或电话通知您。\n\n感谢您的申请！`

      wx.showModal({
        title: successTitle,
        content: successContent,
        showCancel: false,
        confirmText: '确定',
        success: () => {
          wx.navigateBack()
        }
      })
      
    } catch (error) {
      console.error('提交注册申请失败:', error)
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 表单验证
  validateForm() {
    const { registrationType, formData, isEditMode } = this.data

    console.log('🔍 开始表单验证，模式:', isEditMode ? '修改模式' : '新注册模式')

    // 头像验证
    if (!formData.avatar) {
      wx.showToast({
        title: `请上传${registrationType === 'individual' ? '头像' : '公司LOGO'}`,
        icon: 'none'
      })
      return false
    }

    // 通用字段验证
    if (!formData.name.trim()) {
      wx.showToast({ title: '请输入名称', icon: 'none' })
      return false
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({ title: '请输入联系电话', icon: 'none' })
      return false
    }
    
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return false
    }
    
    if (!formData.location || formData.location.trim() === '' || this.data.selectedRegions.length === 0) {
      wx.showToast({ title: '请选择服务地区', icon: 'none' })
      return false
    }
    
    if (!formData.category) {
      wx.showToast({ title: '请选择专业分类', icon: 'none' })
      return false
    }
    
    if (!formData.experience || !formData.experience.trim()) {
      wx.showToast({ title: '请选择从业经验', icon: 'none' })
      return false
    }
    
    if (!formData.specialties.trim()) {
      wx.showToast({ title: '请输入专业技能', icon: 'none' })
      return false
    }
    
    if (!formData.certifications.trim()) {
      wx.showToast({ title: '请输入资质证书', icon: 'none' })
      return false
    }
    
    // 个人师傅特有字段验证
    if (registrationType === 'individual') {
      if (!formData.realName.trim()) {
        wx.showToast({ title: '请输入真实姓名', icon: 'none' })
        return false
      }
      
      if (!formData.idCard.trim()) {
        wx.showToast({ title: '请输入身份证号', icon: 'none' })
        return false
      }
      
      if (!/^\d{17}[\dXx]$/.test(formData.idCard)) {
        wx.showToast({ title: '请输入正确的身份证号', icon: 'none' })
        return false
      }
    }
    
    // 公司特有字段验证
    if (registrationType === 'company') {
      if (!formData.companyName.trim()) {
        wx.showToast({ title: '请输入公司全称', icon: 'none' })
        return false
      }
      
      if (!formData.businessLicense.trim()) {
        wx.showToast({ title: '请输入营业执照号', icon: 'none' })
        return false
      }
      
      if (!formData.legalRepresentative.trim()) {
        wx.showToast({ title: '请输入法定代表人', icon: 'none' })
        return false
      }
      
      if (!formData.registeredCapital.trim()) {
        wx.showToast({ title: '请输入注册资本', icon: 'none' })
        return false
      }
      
      if (!formData.companyAddress.trim()) {
        wx.showToast({ title: '请输入公司地址', icon: 'none' })
        return false
      }
    }
    
    return true
  },

  // 重置表单
  resetForm() {
    wx.showModal({
      title: '确认重置',
      content: '确定要清空所有已填写的内容吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            formData: {
              name: '',
              phone: '',
              location: '',
              category: '',
              experience: '',
              description: '',
              specialties: '',
              certifications: '',
              realName: '',
              idCard: '',
              companyName: '',
              businessLicense: '',
              legalRepresentative: '',
              registeredCapital: '',
              companyAddress: ''
            },
            categoryIndex: 0,
            currentCategoryName: '请选择专业分类'
          })
          
          wx.showToast({
            title: '表单已重置',
            icon: 'success'
          })
        }
      }
    })
  }
})
